﻿#include "XlsxAdapter.h"
#include"Tools.h"
#include<QDateTime>
#include"ThreadEnumFile.h"

XlsxAdapter::XlsxAdapter(QObject *parent) :
    mAccessIsInit(false),
    mIsRun(true),
    QObject(parent)
{
    QString indexStr = readConfig("accessIndex").toString();
    mAccIndex =  indexStr.isEmpty()? -1: indexStr.toInt();
    if(mAccIndex < 2) mAccIndex = 2;

}

XlsxAdapter::~XlsxAdapter()
{
    xPrint;
    mIsRun = false;
    msleep(100);
    if(file.isOpen()){
        file.write(mContent.toLocal8Bit());
        file.close();
    }
    writeConfig("accessIndex",mAccIndex);
    mXlDoc->deleteLater();

}

void XlsxAdapter::setSuffix(QString suffix)
{
    if(suffix == "all")
       mSuffixList<<"mkv"<<"mpg"<<"mp4";
    else mSuffixList<<suffix;
}

void XlsxAdapter::setSavePath(QString savePath)
{
    mSavePath = savePath;
}

void XlsxAdapter::onInitAccess(QString filename, int tableIndex,int customerId)
{
    if(mAccessIsInit) return;
    xPrint<<filename<<customerId;
    mCustomerId = customerId;
    mXlDoc = new QXlsx::Document(filename,this);
    QStringList sheetNames = mXlDoc->sheetNames();
    xPrint<<sheetNames;

    mWorkSheet = static_cast<QXlsx::Worksheet*>(mXlDoc->sheet(sheetNames.at(0)));

    int intRowStart = mWorkSheet->dimension().firstRow();
    mRowsEndPos = mWorkSheet->dimension().lastRow();
    mColsStartPos = mWorkSheet->dimension().firstColumn();
    mColsEndPos = mWorkSheet->dimension().lastColumn();
    if( mAccIndex == -1) mAccIndex = intRowStart + 2;
    mAccessIsInit = true;
    xPrint<<mRowsEndPos<<mColsEndPos;
    mColsEndPos = 5;

}

void XlsxAdapter::onRunTask()
{
    while (mIsRun) {
        if(!mAccessIsInit){
           msleep(100);
           continue;
        }
        break;
    }


    if(!openWriteFile()) return;

    static int _lastProgess = 0;

    mWriteCount = 0;
   if(file.size() > 1024 * 1024*2)
       mWriteCount = 9990;

    while (mIsRun) {
     QString object = getSongInfo();

     int currentProgess = mAccIndex * 100 /mRowsEndPos;
     ++mWriteCount;
     if(_lastProgess != currentProgess){
         _lastProgess = currentProgess;
        emit progessValue( _lastProgess);
     }

      if(mWriteCount == 10000 || mAccIndex == mRowsEndPos + 1){
          mContent += object;
          file.write(mContent.toLocal8Bit());
          mContent.clear();
          addBrackets();
          writeConfig("accessIndex",mAccIndex);
          QString newname = getNewName();
          QFile::rename("access.json",newname);
          if( mAccIndex == mRowsEndPos+1)
              break;

          if(!openWriteFile()) return;
          mWriteCount = 0; 
            continue;

      } else if(!object.isEmpty()){
            mContent += object + ",";
      }
      if(mContent.length() > 1024*256){
          file.write(mContent.toLocal8Bit());
          file.flush();
          mContent = "";
      }

    }
    xPrint<<"task finished......";
    emit packageOver();
    mAccIndex = 2;
    writeConfig("accessIndex",mAccIndex);
    mAccessIsInit = false;
}


QString XlsxAdapter::getSongInfo()
{

    if(mAccIndex == mRowsEndPos+1){
        return QString();
    }
    QString rowStr;
    for (int j = mColsStartPos; j <= mColsEndPos; j++)
    {
        QXlsx::Cell *cell = mWorkSheet->cellAt(mAccIndex, j);
        if(!cell) {
            mAccIndex++ ;
            return QString("{}");
        }
        rowStr = rowStr + cell->value().toString() +",";
        delete cell;
    }
    mAccIndex++;
//    xPrint<<rowStr;

    return productJson(rowStr);
}

void XlsxAdapter::addBrackets()
{
    file.write(QString("]").toLatin1());
    file.close();
}

void XlsxAdapter::winMoveFile(QString oldfile, QString newfile)
{
    CopyFile((LPCWSTR)oldfile.toStdWString().c_str(),(LPCWSTR)newfile.toStdWString().c_str(),true);
}

bool XlsxAdapter::openWriteFile()
{
    file.setFileName("access.json");
    if(!file.exists()) mContent = "[";
    if(!file.open(QIODevice::ReadWrite|QIODevice::Append)){
        xPrint<<"wirtefile failed";
        return false;
    }
    if(file.readAll().size() == 0) mContent = "[";
    return true;
}

QString XlsxAdapter::getNewName()
{
    for(int m = 1;m < 1000;++m){
      QString newname = QString("access_upload%1.json").arg(m);
      if(!QFile::exists(newname))
          return newname;
    }
    return QString();
}

QString XlsxAdapter::productJson(QString songInfo)
{
    QStringList infoList =songInfo.split(",");

    QString id = infoList.at(0);
    QString songName = infoList.at(1);
    QString hSinger = infoList.at(2);
    QString language = infoList.at(3);
    songName = songName.replace("'",tr("’"));
    hSinger = hSinger.replace("'",tr("’"));
    language = language.replace("'",tr("’"));
    int filesize = 0;

    QString ofile = qDirHander.getOldName(id.toInt());
    if(ofile.isEmpty()) {
        xErr <<"file is not exist:"<<id;
        return QString("{}");
    }

    QString mtvNamePY= QString();
    QString mtvNameAbbrev = QString();
    QString startNamePY = QString();
    QString starNameAbbrev = QString();
    try{
        mPinYingAdapter.pinyinParse(songName,mtvNamePY,mtvNameAbbrev);
        mPinYingAdapter.pinyinParse(hSinger,startNamePY,starNameAbbrev);
    }catch(...){
        xPrint<<"ping ying error";
    }


    QString roopth;

    int mid = ofile.indexOf("/",2);
    roopth = ofile.mid(mid);

    if(!mSavePath.isEmpty()){
        mSuffix = QFileInfo(ofile).suffix();
       if(!ofile.isEmpty()){
           QString nfile =  QString("%1/%2.%3").arg(mSavePath).arg(id).arg(mSuffix);
           winMoveFile(ofile,nfile);
           mid = nfile.indexOf("/",2);
           roopth = nfile.mid(mid);
       }
    }


    QJsonObject obj;
    obj.insert("mtvName",songName);
    obj.insert("starName",hSinger);
    obj.insert("mtvNamePY",mtvNamePY);
    obj.insert("mtvNameAbbrev",mtvNameAbbrev);
    obj.insert("startNamePY",startNamePY);
    obj.insert("starNameAbbrev",starNameAbbrev);
    obj.insert("language",language);
    obj.insert("fileName",roopth);
    obj.insert("fileUrl","");//m_ftpPath+info->songName()todo
    obj.insert("fileSize",filesize);
    obj.insert("customerId",mCustomerId);
    QString content = QString(QJsonDocument(obj).toJson());
    return content;
}
